package com.leyou.sms.mq;

import com.leyou.common.constants.MQConstants.*;
import com.leyou.common.utils.RegexUtils;
import com.leyou.sms.util.SmsUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.Map;

@Slf4j
@Component
public class MessageListener {
    @Autowired
    private SmsUtil smsUtil;

    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(name = QueueConstants.SMS_VERIFY_CODE_QUEUE,durable = "true"),
            exchange = @Exchange(name = ExchangeConstants.SMS_EXCHANGE_NAME,type = ExchangeTypes.TOPIC),
            key = RoutingKeyConstants.VERIFY_CODE_KEY
    ))
    public void listenerSendCodeMessage(Map<String,String> msg){
        //获取参数
        if (CollectionUtils.isEmpty(msg)){
            //消息为空
            return;
        }
        //手机号
        if (!RegexUtils.isPhone(msg.get("phone"))){
            //手机号有误
            return;
        }
        //验证码
        if (!RegexUtils.isCodeValid(msg.get("code"))){
            //验证码有误
            return;
        }

        //发送短信
        try{
            smsUtil.sendVerifyCode(msg.get("phone"),msg.get("code"));
        }catch (Exception e) {
            log.error("【SMS服务】短信验证码发送失败", e);
        }
    }



}
